package com.h3c.nem.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.h3c.nem.dto.TbPreWorkerDTO;
import com.h3c.nem.dto.TbPreWorkerSeaDTO;
import com.h3c.nem.service.CommService;
import com.h3c.nem.service.ISdDeptService;
import com.h3c.nem.service.ITbPreWorkerService;
import com.h3c.nem.utils.AppBusinessException;
import com.h3c.nem.utils.BusiEnumDefine;
import com.h3c.nem.utils.ReturnCodeData;
import com.h3c.nem.utils.ReturnDataUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: TbPreWorkerController
 *
 * @Author: l22886
 * @Date: 2022-01-19
 * Description: tb_pre_worker controller
 * Version: 1.0
 */
@Api(tags = " TbPreWorker 接口")
@Slf4j
@RestController
@CrossOrigin
@RequestMapping(value = "/tbPreWorker",produces = "application/json;charset=utf-8")
public class TbPreWorkerController {

    @Resource
    private ITbPreWorkerService tbPreWorkerService;
    @Resource
    private ISdDeptService deptService;
    @Resource
    private CommService commService;

    /**
     * @title: queryFuzzyListForPage
     * @description: 列表分页模糊查询
     * @params: [ paramsDTO, currentPage, pageSize ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "待入职员工列表分页查询", notes = "列表分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbPreWorkerDTO", paramType = "query"),
        @ApiImplicitParam(name = "currentPage", value = "当前页", required = true, dataType = "Integer", paramType = "query"),
        @ApiImplicitParam(name = "pageSize", value = "一页数据条数", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping(value = "/queryFuzzyListForPage", method = RequestMethod.GET)
    public ResponseEntity<JSONObject> queryFuzzyListForPage(@ModelAttribute TbPreWorkerSeaDTO paramsDTO,
                                                            @RequestParam(name = "currentPage", required = true) Integer currentPage,
                                                            @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        log.info("准备执行  列表分页模糊查询，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            if (!StringUtils.isEmpty(paramsDTO.getDeptIds())) {
                paramsDTO.setDeptIdSet(deptService.getDeptChildIds(paramsDTO.getDeptIds()));
            }
            String loginUserRole = commService.getLoginUserRole();
            boolean adminAuth = commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_ADMIN);
            boolean bpAuth = commService.checkLoginUserBP();
            boolean conAuth = commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_DEPT_CONTACTOR);
            boolean manAuth = commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_DEPT_MANAGER);
            if (adminAuth){
            }else if(bpAuth || conAuth || manAuth){
                Set<Integer> authDeptIds = deptService.getAuthDeptIds(bpAuth, conAuth, manAuth, false);
                if (paramsDTO.getDeptIdSet() != null) {
                    paramsDTO.getDeptIdSet().retainAll(authDeptIds);
                }else{
                    paramsDTO.setDeptIdSet(authDeptIds);
                }
            }else{
                Page<TbPreWorkerDTO> page = PageHelper.startPage(currentPage, pageSize);
                PageInfo<TbPreWorkerDTO> pageInfo = page.toPageInfo();
                pageInfo.setList(new LinkedList<>());
                data.put("data",pageInfo);
                data.put("msg", "列表分页模糊查询成功");
                data.put("code", ReturnCodeData.SUCCESS);
            }
            //分页
            Page<TbPreWorkerDTO> page = PageHelper.startPage(currentPage, pageSize);
            //执行
            List<TbPreWorkerDTO> resultDTOList = tbPreWorkerService.selectFuzzyByDto(paramsDTO);
            PageInfo<TbPreWorkerDTO> pageInfo = page.toPageInfo();
            data.put("data",pageInfo);
            data.put("msg", "列表分页模糊查询成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行列表分页模糊查询异常，异常信息为：" + JSON.toJSONString(e));
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行列表分页模糊查询完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    /**
     * @title: save
     * @description: 数据插入
     * @params: [ paramsDTO ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "数据插入", notes = "数据插入")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbPreWorker", paramType = "body")})
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> save(@RequestBody TbPreWorkerDTO paramsDTO) {
        log.info("准备执行 数据插入，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //执行
            Integer result = tbPreWorkerService.insertDto(paramsDTO);
            data.put("data",result);
            data.put("msg", "数据插入成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行 数据插入 异常，异常信息为：" + JSON.toJSONString(e));
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行 数据插入完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    /**
     * @title: update
     * @description: 数据修改
     * @params: [ paramsDTO ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "数据修改", notes = "数据修改")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbPreWorker", paramType = "body")})
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> update(@RequestBody TbPreWorkerDTO paramsDTO) {
        log.info("准备执行 数据修改，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //执行
            Integer result = tbPreWorkerService.updateDto(paramsDTO);
            data.put("data",result);
            data.put("msg", "数据修改成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行 待入职员工数据修改 异常，异常信息为：" + JSON.toJSONString(e));
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行 数据修改完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    @PostMapping("confirmChangePlanDate")
    public ResponseEntity<JSONObject> confirmChangePlanDate(@RequestBody TbPreWorkerDTO param){
        log.info("确认变更时间，入参： " + param.toString());
        tbPreWorkerService.confirmChangePlanDate(param);
        log.info("确认变更时间，成功");
        return new ReturnDataUtil().success();
    }

    @RequestMapping(value = "/updatePlanTime", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> updatePlanTime(@RequestBody TbPreWorkerDTO paramsDTO) {
        log.info("准备执行 从hrss修改计划入职时间，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //执行
            tbPreWorkerService.updatePlanTime(paramsDTO);
            data.put("msg", "数据修改成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行 待入职员工数据修改 异常，异常信息为：" + JSON.toJSONString(e));
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行 数据修改完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    @GetMapping("calenderStatistics")
    public ResponseEntity<JSONObject> calenderStatistics(@RequestParam("time")String time,
                                                         @RequestParam(value = "deptId",required = false)String deptId){
        log.info("准备执行 待入职员工日历查询，传入的参数为：time=" + time + "deptId=" + deptId);
        Map<String,Map<Object,Object>> resList = tbPreWorkerService.calenderStatistics(time, deptId);
        return new ReturnDataUtil().success(resList);
    }

    /**
     * @title: delete
     * @description: 数据删除
     * @params: [ id ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "数据删除", notes = "数据删除")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbPreWorker", paramType = "body")})
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> delete(@RequestBody TbPreWorkerDTO paramsDTO) {
        log.info("准备执行 数据删除，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //执行
            Integer result = tbPreWorkerService.deleteDto(paramsDTO);
            data.put("data",result);
            data.put("msg", "数据删除成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行 数据删除 异常，异常信息为：" + JSON.toJSONString(e));
            data.put("msg", "数据删除失败");
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行 数据删除 完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    @PostMapping("exportPreWorker")
    public ResponseEntity<JSONObject> exportPreWorker(@RequestBody TbPreWorkerSeaDTO paramsDTO){
        log.info("准备执行 数据插入，传入的参数为：" + JSON.toJSONString(paramsDTO));
        try {
            if (!StringUtils.isEmpty(paramsDTO.getDeptIds())) {
                paramsDTO.setDeptIdSet(deptService.getDeptChildIds(paramsDTO.getDeptIds()));
            }
            String loginUserRole = commService.getLoginUserRole();
            boolean adminAuth = commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_ADMIN);
            boolean bpAuth = commService.checkLoginUserBP();
            boolean conAuth = commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_DEPT_CONTACTOR);
            boolean manAuth = commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_DEPT_MANAGER);
            if (adminAuth){
            }else if(bpAuth || conAuth || manAuth){
                Set<Integer> authDeptIds = deptService.getAuthDeptIds(bpAuth,conAuth,manAuth,false);
                if (paramsDTO.getDeptIdSet() != null) {
                    paramsDTO.getDeptIdSet().retainAll(authDeptIds);
                }else{
                    paramsDTO.setDeptIdSet(authDeptIds);
                }
            }
            File file = tbPreWorkerService.exportPreWorker(paramsDTO);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            fileInputStream.read(buffer);
            fileInputStream.close();
            Map<String, String> result = new HashMap<>();
            result.put("file", Base64Utils.encodeToString(buffer));
            result.put("filename", file.getName());
            log.info("导出成功");
            return new ReturnDataUtil().success(result);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("导出error:" + e.getMessage());
            throw new AppBusinessException("导出出错");
        }

    }

    @PostMapping("importPreWorker")
    public ResponseEntity<JSONObject> importPreWorker(MultipartFile file){
        log.info("执行待入职员工信息导入");
        tbPreWorkerService.importPreWorker(file);
        log.info("执行待入职员工信息导入finish success");
        return new ReturnDataUtil().success();
    }

    /**
     * 预备员工发送通知
     * 不用！
     * @param workerIds
     * @return
     */
    @PostMapping("sendMessageToTeacher")
    public ResponseEntity<JSONObject> sendMessageToTeacher(@RequestBody List<String> workerIds){
//        tbPreWorkerService.sendMessageToTeacher(workerIds);
        return new ReturnDataUtil().success();
    }


}
